package warmachineroster.grapheditor.dnd;

import java.util.List;

import org.eclipse.gef.EditPartViewer;
import org.eclipse.gef.Request;
import org.eclipse.gef.commands.Command;
import org.eclipse.gef.dnd.AbstractTransferDropTargetListener;
import org.eclipse.gef.requests.CreateRequest;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DropTargetEvent;

import warmachinesystem.BaseUnit;


public class RosterDropTargetListener extends
		AbstractTransferDropTargetListener {

	private WarmachineRosterCreationFactory factory;

	public RosterDropTargetListener(EditPartViewer viewer) {
		super(viewer, OutlineToRosterTransfer.getInstance());
	}

	@SuppressWarnings("unchecked")
	protected Request createTargetRequest() {
		CreateRequest req = new CreateRequest();
		List<BaseUnit> transfer = ((OutlineToRosterTransfer) getTransfer()).getBaseUnits();
		req.getExtendedData().put(OutlineToRosterTransfer.TYPE_NAME, transfer);
		if (factory == null)
			factory = new WarmachineRosterCreationFactory();
		factory.setTransferredObjects(transfer);
		req.setFactory(factory);
		return req;
	}

	protected void handleDragOver() {
		getCurrentEvent().detail = DND.DROP_COPY;
		super.handleDragOver();
	}

	// Over-ridden so that the cursor can be updated to "disallow" when the
	// command is
	// not executable
	public boolean isEnabled(DropTargetEvent event) {
		boolean result = super.isEnabled(event);
		if (result) {
			updateTargetRequest();
			updateTargetEditPart();
			Command cmd = getCommand();
			result = cmd != null && cmd.canExecute();
		}
		return result;
	}

	protected void updateTargetRequest() {
		CreateRequest req = (CreateRequest) getTargetRequest();
		req.setLocation(getDropLocation());
	}

}
